<?php

use LucaDegasperi\OAuth2Server\Authorizer;
use Rootant\Api\Exception\DuplicateOperationException;

class CommentController extends CommonController
{

    protected $userId = '';

    protected $userIp = '';

    public function __construct(Authorizer $authorizer)
    {
        parent::__construct($authorizer);
        $this->beforeFilter('oauth', ['except' => ['anonymousReply']]);
        $this->beforeFilter('validation');
    }

    private static $_validate = [
        'favour' => [
            'flag' => 'required|in:1,2,3',
        ],
        'unfavour' => [
            'flag' => 'required|in:1,2,3',
        ],
        'reply' => [
            'content' => 'required',
            'flag' => 'required|in:1,2,3',
        ],
        'anonymousReply' => [
            'content' => 'required',
            'flag' => 'required|in:1,2,3',
        ],
    ];

    /**
     * 用户评论点赞
     *
     * @param  string $id        文章id
     * @param  string $commentId 文章评论id
     * @return array
     */
    public function favour($id, $commentId)
    {
        $this->userId = $this->authorizer->getResourceOwnerId();

        $this->flag = Input::get('flag');

        if ($this->checkUserFavour($this->userId, $commentId)) {
            throw new DuplicateOperationException('您已点赞:)');
        }

        $insertData = array(
                'user_id'            => $this->userId,
                'article_comment_id' => $commentId,
                'flag'               => $this->flag,
                'created_at'         => date('Y-m-d H:i:s'),
            );
        // 手动开启一个事务
        DB::beginTransaction();
        try {
            $insertId = DB::table('favour')->insertGetId($insertData);
            // 文章评论被点赞数量 +1
            $this->operator = '+';
            $this->updateCommentFavours($commentId);
            // 存储文章评论点赞相关信息到用户的消息数据表
            $this->content = '赞了这条评论:)';
            $this->storeInformation($commentId, 1);
            // 提交事务
            DB::commit();
            // 赞返回数据
            return $this->favourResponse($commentId);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
            throw new ApiException;
        }
    }

    /**
     * [favourResponse description]
     * @param  int    $insertId  [description]
     * @param  string $commentId [description]
     * @return object stdClass
     */
    protected function favourResponse($commentId)
    {
        list($connection, $table) = $this->getConnection();

        $favours = DB::connection($connection)
            ->table($table)
            ->where('id', $commentId)
            ->pluck('favours');

        return [
            'article_comment_id' => $commentId,
            'favours' => $favours,
        ];
    }

    /**
     * 文章评论取消点赞
     *
     * @param  string $id        文章id
     * @param  string $commentId 文章评论id
     * @return object
     */
    public function unfavour($id, $commentId)
    {
        $this->userId = $this->authorizer->getResourceOwnerId();

        $this->flag = Input::get('flag');

        // 手动开启一个事务
        DB::beginTransaction();
        try {
            // 取消点赞操作
            $items = DB::table('favour')
                ->where('user_id', $this->userId)
                ->where('article_comment_id', $commentId)
                ->where('flag', $this->flag)
                ->delete();

            // 表示删除了一条数据
            if ($items === 1) {
                // 文章评论被点赞数量 -1
                $this->operator = '-';
                $this->updateCommentFavours($commentId);
                // 存储文章评论取消点赞相关信息到用户的消息数据表
                $this->content = '取消了这条评论的赞:(';
                $this->storeInformation($commentId, 1);
            }
            // 提交事务
            DB::commit();
            // 赞返回数据
            return $this->favourResponse($commentId);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
            throw new ApiException;
        }
    }

    /**
     * 存储相关信息到消息数据表
     *
     * @param  string  $commentId 文章评论id
     * @param  integer $type      消息类型：1-评论点赞/取消点赞，2-评论回复
     * @return void
     */
    protected function storeInformation($commentId, $type)
    {
        if ($this->flag != '2') {
            return;
        }

        $contentInfo = $this->infoIntersection($commentId);

        $insertData = array(
                'type'       => $type,
                'content'    => serialize($contentInfo), // 存储序列化后的内容
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            );

        if ($this->userId !== '') {
            $insertData = array_merge($insertData, ['from_uid' => $this->userId]);
        } else {
            $insertData = array_merge($insertData, ['from_user_ip' => $this->userIp]);
        }

        if ($this->uid === null) {
            $insertData = array_merge($insertData,
                    ['to_user_ip' => $this->uip, 'unread_user_ip' => $this->uip]
                );
        } else {
            $insertData = array_merge($insertData,
                    ['to_uid' => $this->uid, 'unread_uid' => $this->uid]
                );
        }

        // 持久化存储数据
        $this->models['information']->insert($insertData);
    }

    /**
     * 存储消息的公共部分
     *
     * @param  string $commentId 文章评论id
     * @return object
     */
    protected function infoIntersection($commentId)
    {
        $this->models['information']     = DB::table('information');
        $this->models['article_comment'] = DB::table('article_comment');

        return array_merge(
            ['reply' => $this->content],
            ['comment' => (array) $this->articleComment($commentId)]
        );
    }

    /**
     * 获取文章评论的信息
     *
     * @param  string $commentId 文章的评论id
     * @return object stdClass
     */
    protected function articleComment($commentId)
    {
        $comment = $this->models['article_comment']
            ->select('id', 'user_id', 'user_ip', 'article_id', 'created_at', 'content', 'favours')
            ->find($commentId);

        $this->uid = $comment->user_id;
        $this->uip = $comment->user_ip;
        // 获取评论所属用户信息
        $comment->owner = $this->getOwner();
        // release some field
        unset($comment->user_id, $comment->user_ip, $comment->favours);

        return $comment;
    }

    /**
     * 文章评论的回复
     *
     * @param  string $id        文章id
     * @param  string $commentId 文章评论id
     * @return array
     */
    public function reply($id, $commentId)
    {
        $this->userId = $this->authorizer->getResourceOwnerId();

        $this->flag = Input::get('flag');

        $insertData = $this->replyIntersection($commentId);
        $insertData = array_merge($insertData, ['user_id' => $this->userId]);

        // 手动开启一个事务
        DB::beginTransaction();
        try {
            // 存储评论回复信息
            $insertId = $this->models['reply']->insertGetId($insertData);
            // 存储文章评论回复相关信息到用户的消息数据表
            $this->content = '回复：'.Input::get('content');
            $this->storeInformation($commentId, 2);
            // 提交事务
            DB::commit();

            return $this->replyResponse($insertId);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
            throw new ApiException;
        }
    }

    /**
     * 文章评论的回复响应数据
     *
     * @param  int   $id 文章评论回复id
     * @return array
     */
    protected function replyResponse($id)
    {
        $replyResult = $this->models['reply']
            ->select('id', 'created_at', 'content')
            ->find($id);

        $this->uid = ($this->userId === '') ? null : $this->userId;
        $this->uip = $this->userIp;

        $replyResult->user = $this->getOwner();

        return (array) $replyResult;
    }

     /**
     * 匿名用户回复文章评论
     *
     * @param  string $id        文章id
     * @param  string $commentId 文章评论id
     */
    public function anonymousReply($id, $commentId)
    {
        // 校验验证码
        MultiplexController::verifyCaptcha();

        $this->flag = Input::get('flag');

        $this->userIp = Request::ip();
        $insertData = $this->replyIntersection($commentId);
        $insertData = array_merge($insertData, ['user_ip' => $this->userIp]);
        // 手动开启一个事务
        DB::beginTransaction();
        try {
            // 存储评论回复信息
            $insertId = $this->models['reply']->insertGetId($insertData);
            // 存储匿名回复信息
            $this->content = '回复：'.Input::get('content');
            $this->storeInformation($commentId, 2);
            // 提交事务
            DB::commit();

            return $this->replyResponse($insertId);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
            throw new ApiException;
        }
    }

    /**
     * 匿名回复/回复评论提取公共代码
     *
     * @param  string $commentId  文章评论id
     * @return array  $insertData 插入数据库公共数据
     */
    protected function replyIntersection($commentId)
    {
        $this->content = Input::get('content');

        $this->models['reply'] = DB::table('reply');

        return array(
                'article_comment_id' => $commentId,
                'content'            => $this->content,
                'flag'               => $this->flag,
                'created_at'         => date('Y-m-d H:i:s'),
                'updated_at'         => date('Y-m-d H:i:s'),
            );
    }

}